﻿using ESRI.ArcGIS;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Geodatabase;
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using ESRI.ArcGIS.DataSourcesFile;
using ESRI.ArcGIS.Geometry;

namespace Mygisdzy
{
    public partial class AttributeForm : Form
    {
        public string strOutputPath; // 输出路径
        private IMapControl3 _mapControl; // 地图控件引用

        // 构造函数：接收地图控件
        public AttributeForm(object mapControl)
        {
            InitializeComponent();
            _mapControl = mapControl as IMapControl3;
            InitializeLayerList(); // 初始化图层列表
        }
        private void InitializeLayerList()
        {
            for (int i = 0; i < _mapControl.LayerCount; i++)
            {
                ILayer layer = _mapControl.get_Layer(i);
                if (layer is IFeatureLayer)
                {
                    IFeatureLayer featureLayer = (IFeatureLayer)layer;
                    // 仅显示多边形图层
                    if (featureLayer.FeatureClass.ShapeType == esriGeometryType.esriGeometryPolygon)
                    {
                        cmbLayer.Items.Add(layer.Name);
                    }
                }
            }
            if (cmbLayer.Items.Count > 0) cmbLayer.SelectedIndex = 0;
        }
        
        private void btnOK_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtCondition.Text) || cmbLayer.SelectedIndex == -1)
            {
                MessageBox.Show("请选择图层并输入查询条件！");
                return;
            }
            try
            {
                // 1. 获取目标图层
                IFeatureLayer featureLayer = GetSelectedLayer(cmbLayer.SelectedItem.ToString());
                IFeatureClass featureClass = featureLayer.FeatureClass;
                // 2. 构建查询过滤器
                IQueryFilter queryFilter = new QueryFilterClass();
                queryFilter.WhereClause = txtCondition.Text;

                // 3. 执行查询
                IFeatureCursor featureCursor = featureClass.Search(queryFilter, true);

                // 4. 导出结果到新Shapefile
                strOutputPath = txtOutputPath.Text;
                ExportToShapefile(featureCursor, featureClass.Fields, strOutputPath);

                // 5. 关闭对话框
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("查询失败: " + ex.Message);
            }
            finally
            {
                GC.Collect(); // 强制清理COM对象
            }
        }
        // 导出要素到Shapefile
        private void ExportToShapefile(IFeatureCursor cursor, IFields fields, string outputPath)
        {
            // 解析路径
            string directory = System.IO.Path.GetDirectoryName(outputPath);
            string fileName = System.IO.Path.GetFileNameWithoutExtension(outputPath);
            // 创建新要素类
            IWorkspaceFactory workspaceFactory = new ShapefileWorkspaceFactoryClass();
            IFeatureWorkspace workspace = (IFeatureWorkspace)workspaceFactory.OpenFromFile(directory, 0);
            IFeatureClass outputClass = workspace.CreateFeatureClass(fileName, fields, null, null, esriFeatureType.esriFTSimple, "Shape", "");
            // 复制要素
            IFeature outputFeature;
            IFeature inputFeature = cursor.NextFeature();
            while (inputFeature != null)
            {
                outputFeature = outputClass.CreateFeature();
                outputFeature.Shape = inputFeature.ShapeCopy;
                for (int i = 0; i < outputClass.Fields.FieldCount; i++)
                {
                    string fieldName = outputClass.Fields.get_Field(i).Name;
                    if (!fieldName.Equals("Shape") && !fieldName.Equals(outputClass.OIDFieldName))
                    {
                        outputFeature.set_Value(i, inputFeature.get_Value(i));
                    }
                }
                outputFeature.Store();
                inputFeature = cursor.NextFeature();
            }
            Marshal.ReleaseComObject(cursor);
        }
        // 根据图层名称获取图层对象
        private IFeatureLayer GetSelectedLayer(string layerName)
        {
            for (int i = 0; i < _mapControl.LayerCount; i++)
            {
                ILayer layer = _mapControl.get_Layer(i);
                if (layer.Name.Equals(layerName))
                {
                    return (IFeatureLayer)layer;
                }
            }
            return null;// 未找到图层
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }
       
        private void btnBrowse_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveDialog = new SaveFileDialog();
            saveDialog.Filter = "Shapefile (*.shp)|*.shp";// 文件类型过滤
            if (saveDialog.ShowDialog() == DialogResult.OK)
            {
                txtOutputPath.Text = saveDialog.FileName;// 更新路径文本框
            }
        }
    }
}
